# _*_ coding:utf-8 _*_

from Tkinter import *
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import datetime

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET


matplotlib.rcParams.update({'font.size': 6})


def split(line):
    return int(float(line.strip()))


def read_file(filename, func):
    dataset = [0]
    fp = open(filename, "rb")
    for line in fp.readlines():
        dataset.append(func(line))
    return dataset


def load_rou_xml(filename):
    dataset = [0]
    for event, elem in ET.iterparse(filename):
        if event == 'end':
            if elem.tag == 'vehicle':
                dataset.append(int(float(elem.attrib['depart'])))
    return dataset


def count_x_minutes(data, x):
    result = {}
    print ('x is {0}'.format(x))
    intervals = x * 60
    for item in data:
        key = item / intervals
        result.setdefault(key, 0)
        result[key] += 1
    return sorted(result.iteritems(), key=lambda d: d[0], reverse=False)


def transfer_to_time_format(x):
    hour = x / 60
    minute = x % 60
    day = hour / 24 + 1
    hour %= 24
    str = "%d %02d:%02d" % (day, hour, minute)
    # str = "%02d:%02d" % (hour, minute)
    print str
    return datetime.datetime.strptime(str, "%d %H:%M")


def test_transfer_to_time_format():
    x = 100
    print("after transfer_to_time_format: {0}".format(transfer_to_time_format(x)))


def redraw(var):
    redraw.f.clf()
    redraw.a = redraw.f.add_subplot(111)
    tuples = count_x_minutes(data, int(var))
    x = [item[0] * int(var) for item in tuples]
    y = [item[1] for item in tuples]

    x = map(transfer_to_time_format, x)
    print x
    # dates = matplotlib.dates.date2num(x)

    redraw.a.plot_date(x, y)
    redraw.a.set_title('Car-Time Distribution')
    # xlabels = redraw.a.get_xticklabels()
    # redraw.a.set_xlim(x[1], x[-1])
    redraw.f.autofmt_xdate()
    redraw.canvas.show()


if '__main__' == __name__:
    root = Tk()
    Scale(root, from_=1, to=60, orient=HORIZONTAL, resolution=1, label='Interval(minutes)', command=redraw, length=200).\
        grid(row=0, column=1)

    # load data
    # data = read_file('../../data/LuSTScenario.internal.mobility.agg.depart.txt', split)
    # data = read_file('../../data/hangzhou08.depart.txt', split)
    data = load_rou_xml("../../data/1030/10301545.rou.xml")
    redraw.f = Figure(figsize=(5, 4), dpi=150)
    redraw.canvas = FigureCanvasTkAgg(redraw.f, master=root)
    redraw.canvas.show()
    redraw.canvas.get_tk_widget().grid(row=1, columnspan=3)
    root.mainloop()
